package com.yicong.ants.manager.app;

import static com.tencent.qcloud.tuicore.TUIConstants.TUIChat.C2C_CHAT_ACTIVITY_NAME;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import com.cchao.simplelib.core.AndroidHelper;
import com.tencent.qcloud.tuikit.tuiconversation.presenter.ConversationPresenter;
import com.zx.sdk.ZxSDK;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cch
 * @version 2021/6/5
 */
public class AntActivityListener implements Application.ActivityLifecycleCallbacks {

    public static int mStartedActivityCount = 0;
    public Activity mTopActivity;
    static List<Activity> mActivityList = new ArrayList<>();

    public static boolean isAppVisible() {
        return mStartedActivityCount > 0;
    }

    public static void exitApp() {
        try {
            for (Activity activity : mActivityList) {
                if (AndroidHelper.isContextDestroyed(activity)) {
                    continue;
                }
                activity.finishAndRemoveTask();
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    private ConversationPresenter presenter;

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        mActivityList.add(activity);
        String name = activity.getClass().getSimpleName();
        if (C2C_CHAT_ACTIVITY_NAME.equals(name)) {
            boolean sta = true;
            for (int i = 0; i < mActivityList.size(); i++) {
                String name2 = mActivityList.get(i).getClass().getSimpleName();
                if ("ConversationActivity".equals(name2)) {
                    sta = false;
                    break;
                }
            }
            if (sta) {
                presenter = new ConversationPresenter();
                presenter.setConversationListener();
            }
        }
    }

    @Override
    public void onActivityStarted(Activity activity) {
        mStartedActivityCount++;
    }

    @Override
    public void onActivityResumed(Activity activity) {
        mTopActivity = activity;
        ZxSDK.setTopActivity(mTopActivity);
    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {
        mStartedActivityCount--;
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }


    @Override
    public void onActivityDestroyed(Activity activity) {
        mActivityList.remove(activity);
        String name = activity.getClass().getSimpleName();
        if (C2C_CHAT_ACTIVITY_NAME.equals(name)) {
            if (presenter != null) {
                presenter = null;
            }
        }
    }
}
